<?php

namespace App\Admin\Controllers;

use App\Admin\Export\UserWithdrawExport;
use App\Admin\Extensions\PeopleWithdraw;
use App\User;
use App\UserWithdraw;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;

class WithdrawController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('提现申请');
            $content->description('提现申请');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(UserWithdraw::class, function (Grid $grid) {
            $grid->model()->orderBy('created_at', 'desc');
            $grid->id('ID')->sortable();
            $grid->user_name('申请人姓名');
            $grid->bank_code('银行卡号');
            $grid->bank_type('类型')->display(function ($value) {
                return '<img src="' . getBankImg($this->bank_code) . '">';
            });

            $grid->status('状态')->display(function ($value) {
                return UserWithdraw::$statusMap[$value];
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('<a style="float:left;margin-left:10px;" class="btn btn-xs btn-primary" href="' . route('withdraw.show', [$actions->getKey()]) . '">查看</a>');

                // 人工打款
                $actions->append(new PeopleWithdraw(
                        [
                            'btn_name' => '打款',
                            'btn_class' => 'btn-success',
                            'btn_listen'=>'row_people',
                            'title' => '是否确定人工打款',
                            'desc' => '改变数据状态，由人工银行卡转账',
                            'url' => route('withdrawPeople', ['withdraw_id' => $actions->getKey()]),
                        ]
                    )
                );
                // 驳回请求
                $actions->append(new PeopleWithdraw(
                        [
                            'btn_name' => '驳回',
                            'btn_class' => 'btn-warning',
                            'btn_listen'=>'row_refuse',
                            'title' => '是否要驳回请求',
                            'desc' => '驳回请求，余额将退还',
                            'url' => route('withdrawRefuse', ['withdraw_id' => $actions->getKey()]),

                        ]
                    )
                );

            });
            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                //开户姓名
                $filter->like('user_name', '开户姓名');
                // 银行卡号码
                $filter->like('bank_code', '银行卡号');
                // 提现状态
                $filter->equal('status', '状态')->select(UserWithdraw::$statusMap);
                //下单日期范围
                $filter->between('created_at', '申请时间')->datetime();

            });
            $grid->disableCreateButton();
            $grid->exporter(new UserWithdrawExport());
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });
            $grid->price("提现金额");
            $grid->created_at('申请时间');

        });
    }

    public function show(UserWithdraw $withdraw)
    {
        return Admin::content(function (Content $content) use ($withdraw) {
            $content->header('查看提现申请');
            // body 方法可以接受 Laravel 的视图作为参数
            $content->body(view('admin.userWithdraw.show', ['userWithdraw' => $withdraw]));
        });
    }

    /**
     * @param Request $request
     * 调用接口打款
     */
    public function submit(Request $request)
    {
        // dd($request->all());
        $withdraw_id = $request->withdraw_id;

        $userWithdraw = UserWithdraw::find($withdraw_id);
        if ($userWithdraw->status != UserWithdraw::STATUS_PENDING) {
            return Response()->json(['code' => 'error', 'message' => '提现已经处理']);
        }
        $user = User::find($userWithdraw->user_id);
        //todo 微信付款到零钱
        $payment = \EasyWeChat::payment();
        $result = $payment->transfer->toBalance([
            'partner_trade_no' => time(), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $user->openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            //'re_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => (int)$userWithdraw->price * 100, // 企业付款金额，单位为分
            'desc' => '提现', // 企业付款操作说明信息。必填
        ]);

        if ($result['result_code'] == 'FAIL') {
            return Response()->json(['code' => 'error', 'message' => $result['err_code_des']]);
        }
        $userWithdraw->result_message=$request->result_message;
        $userWithdraw->status = UserWithdraw::STATUS_SUBMIT;
        $userWithdraw->save();
        /* if($userWithdraw->price > User::find($userWithdraw->user_id)){
             return Response()->json(
             [
                 'code'=>'error',
                 'message'=>'用户余额不足'
             ]
             );
         }
         User::where('id',$userWithdraw->user_id)->decrement('money',$userWithdraw->price);*/
        return Response()->json(
            [
                'code' => 'success',
                'message' => '提现成功'
            ]
        );
    }

    /**
     * @param Request $request
     * 人工打款
     * 不调用接口
     */
    public function people(Request $request)
    {
        $withdraw_id = $request->withdraw_id;
        $userWithdraw = UserWithdraw::find($withdraw_id);
        if ($userWithdraw->status != UserWithdraw::STATUS_PENDING) {
            return Response()->json(['code' => 'error', 'message' => '提现已经处理']);
        }
        $userWithdraw->result_message=$request->result_message;
        $userWithdraw->status = UserWithdraw::STATUS_PEOPLE;
        $userWithdraw->save();
        /*  if($userWithdraw->price > User::find($userWithdraw->user_id)){
              return Response()->json(
                  [
                      'code'=>'error',
                      'message'=>'用户余额不足'
                  ]
              );
          }
          User::where('id',$userWithdraw->user_id)->decrement('money',$userWithdraw->price);*/
        return Response()->json(
            [
                'code' => 'success',
                'message' => '提现成功'
            ]
        );
    }

    /**
     *
     */
    public function refuse(Request $request)
    {
        $withdraw_id = $request->withdraw_id;
        $userWithdraw = UserWithdraw::find($withdraw_id);
        if ($userWithdraw->status != UserWithdraw::STATUS_PENDING) {
            return Response()->json(['code' => 'error', 'message' => '提现已经处理']);
        }
        User::where('id', $userWithdraw->user_id)->increment('money', $userWithdraw->price);
        $userWithdraw->result_message=$request->result_message;
        $userWithdraw->status = UserWithdraw::STATUS_REFUSE;
        $userWithdraw->save();
        return Response()->json(
            [
                'code' => 'success',
                'message' => '已拒绝'
            ]
        );
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(UserWithdraw::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }
}
